package com.taxi.driver.module.order.address;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.qianxx.utils.TypeUtils;
import com.qianxx.view.wheel.adapter.ArrayWheelAdapter;
import com.qianxx.view.wheel.hh.OnWheelChangedListener;
import com.qianxx.view.wheel.hh.WheelView;
import com.taxi.driver.R;
import com.taxi.driver.common.BaseActivity;
import com.taxi.driver.config.IConstants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 选择城市
 */
public class CitiesActivity extends BaseActivity implements OnWheelChangedListener {

    public final static int RESULT = 99; //成功返回码

    public static void actionStart(Activity context, String province, String city) {
        actionStart(context, province, city, 0);
    }

    public static void actionStart(Activity context, String province, String city, int requestCode) {
        Intent intent = new Intent(context, CitiesActivity.class);
        intent.putExtra("province", TypeUtils.getValue(province));
        intent.putExtra("city", TypeUtils.getValue(city));
        intent.putExtra("area", "");
        intent.putExtra("requestCode", requestCode);
        context.startActivityForResult(intent, 0);
        context.overridePendingTransition(0, 0);
    }

    /**
     * 把全国的省市区的信息以json的格式保存，解析完成后赋值为null
     */
    private JSONObject mJsonObj;
    /**
     * 省的WheelView控件
     */
    private WheelView mProvince;
    /**
     * 市的WheelView控件
     */
    private WheelView mCity;
    /**
     * 区的WheelView控件
     */
    private WheelView mArea;

    /**
     * 所有省
     */
    private String[] mProvinceDatas;
    /**
     * key - 省 value - 市s
     */
    private Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区s
     */
    private Map<String, String[]> mAreaDatasMap = new HashMap<String, String[]>();

    /**
     * 当前省的名称
     */
    private String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    private String mCurrentCityName;
    /**
     * 当前区的名称
     */
    private String mCurrentAreaName = "";

    // 判断是哪个页面
    private int requestCode;

    // 地址
    // private String address;

    // 标题
    private TextView mTvTitle;

    // 省
    private String ProviceName;

    // 市
    private String CityName;

    // 区
    private String AreaName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_citys);
        requestCode = getIntent().getIntExtra("requestCode", 0);
        ProviceName = getIntent().getStringExtra("province");
        CityName = getIntent().getStringExtra("city");
        AreaName = getIntent().getStringExtra("area");
        // address = ProviceName + CityName + AreaName;
        // ToastUtil.getInstance().toast(address);

        initJsonData();

        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mProvince = (WheelView) findViewById(R.id.id_province);
        mCity = (WheelView) findViewById(R.id.id_city);
        mArea = (WheelView) findViewById(R.id.id_area);

        mTvTitle.setText("选择所在地");

        initDatas();
        // 传值，设置第一次显示的内容
        mProvince.setViewAdapter(new ArrayWheelAdapter<String>(this,
                mProvinceDatas));
        // 添加change事件
        mProvince.addChangingListener(this);
        // 添加change事件
        mCity.addChangingListener(this);
        // 添加change事件
        mArea.addChangingListener(this);

        mProvince.setVisibleItems(5);
        mCity.setVisibleItems(5);
        mArea.setVisibleItems(5);
        // 将获取到的数据设置在wheelview上
        mateCities();
        // updateCities();
        // updateAreas();

    }

    // 根据内容得到数组的下标
    private int selecteIndex(String name, String[] array) {

        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(name)) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 从个人中心界面获取到省市匹配数组中的数据，得到它的下标，再将它设置到界面上
     */
    private void mateCities() {
        int pCurrent = selecteIndex(ProviceName, mProvinceDatas);
        mProvince.setCurrentItem(pCurrent);
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
        int cCurrent = selecteIndex(CityName, cities);
        mCity.setCurrentItem(cCurrent);
        mateAreas(cCurrent);
    }

    /**
     * 将个人中心的获得的区匹配数组中的数据，得到它的下标，再将它设置到界面上
     */
    private void mateAreas(int index) {
        try {
            int pCurrent = index;
            mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
            String[] areas = mAreaDatasMap.get(mCurrentCityName);

            if (areas == null) {
                areas = new String[]{""};
            }
            mArea.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
            int aCurrent = selecteIndex(AreaName, areas);
            mArea.setCurrentItem(aCurrent);

        } catch (Exception e) {
        }

    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        try {
            int pCurrent = mCity.getCurrentItem();
            mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
            String[] areas = mAreaDatasMap.get(mCurrentCityName);

            if (areas == null) {
                areas = new String[]{""};
            }
            mArea.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
            mArea.setCurrentItem(0);

            mCurrentAreaName = mAreaDatasMap.get(mCurrentCityName)[0];
        } catch (Exception e) {
        }

    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));

        mCity.setCurrentItem(0);
        updateAreas();
    }

    /**
     * 解析整个Json对象，完成后释放Json对象的内存
     */
    private void initDatas() {
        try {
            JSONArray jsonArray = mJsonObj.getJSONArray("citylist");
            mProvinceDatas = new String[jsonArray.length() - 1];
            for (int i = 0; i < jsonArray.length() - 1; i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);// 每个省的json对象
                String province = jsonP.getString("p");// 省名字

                mProvinceDatas[i] = province;

                JSONArray jsonCs = null;
                try {
                    /**
                     * Throws JSONException if the mapping doesn't exist or is
                     * not a JSONArray.
                     */
                    jsonCs = jsonP.getJSONArray("c");
                } catch (Exception e1) {
                    continue;
                }
                String[] mCitiesDatas = new String[jsonCs.length()];
                for (int j = 0; j < jsonCs.length(); j++) {
                    JSONObject jsonCity = jsonCs.getJSONObject(j);
                    String city = jsonCity.getString("n");// 市名字
                    mCitiesDatas[j] = city;
                    Log.i("", city);
                    JSONArray jsonAreas = null;
                    try {
                        /**
                         * Throws JSONException if the mapping doesn't exist or
                         * is not a JSONArray.
                         */
                        jsonAreas = jsonCity.getJSONArray("a");
                    } catch (Exception e) {
                        continue;
                    }

                    String[] mAreasDatas = new String[jsonAreas.length()];// 当前市的所有区
                    for (int k = 0; k < jsonAreas.length(); k++) {
                        String area = jsonAreas.getJSONObject(k).getString("s");// 区域的名称
                        mAreasDatas[k] = area;
                    }
                    mAreaDatasMap.put(city, mAreasDatas);
                }

                mCitisDatasMap.put(province, mCitiesDatas);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        mJsonObj = null;
    }

    /**
     * 从assert文件夹中读取省市区的json文件，然后转化为json对象
     */
    private void initJsonData() {
        try {
            StringBuffer sb = new StringBuffer();
            InputStream is = getAssets().open("city.json");
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            BufferedReader reader = new BufferedReader(isr);
            String str = null;
            while ((str = reader.readLine()) != null) {
                sb.append(str + "\r\n");
            }
            reader.close();
            mJsonObj = new JSONObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * change事件的处理
     */
    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mProvince) {
            mCurrentCityName = "";
            mCurrentAreaName = "";
            updateCities();
        } else if (wheel == mCity) {
            mCurrentAreaName = "";
            updateAreas();
        } else if (wheel == mArea) {
            try {
                mCurrentAreaName = mAreaDatasMap.get(mCurrentCityName)[newValue];
            } catch (Exception e) {
            }

        }
    }

    public void saveChoose(View view) {
        if (TextUtils.isEmpty(mCurrentProviceName)) {
            toast("请选择省(或直辖市)");
            return;
        }
        if (TextUtils.isEmpty(mCurrentCityName)) {
            toast("请选择市(或区/县)");
            return;
        }
        // 直辖市需处理
        mCurrentCityName = judgeCity();
        // 返回数据
        Intent data = new Intent();
        data.putExtra(IConstants.PROVINCE, mCurrentProviceName);
        data.putExtra(IConstants.CITY, mCurrentCityName);
        setResult(RESULT, data);
        closeAtyWithoutAnim();
    }

    private String judgeCity() {
        for (int i = 0; i < specialCitys.length; i++) {
            if (specialCitys[i].equals(mCurrentProviceName)) return specialCitys[i];
        }
        return mCurrentCityName;
    }

    // 直辖市列表
    private String[] specialCitys = new String[]{"北京", "天津", "上海", "香港", "澳门"};

    public void cancelChoose(View view) {
        closeAtyWithoutAnim();
    }

    public void btnBg(View view) {
        closeAtyWithoutAnim();
    }

    @Override
    public void onBackPressed() {
        closeAtyWithoutAnim();
    }

    private void closeAtyWithoutAnim() {
        finish();
        overridePendingTransition(0, 0);
    }

}
